package com.itzhanshen.activiti;

import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.*;
import org.activiti.bpmn.model.Process;
import org.activiti.engine.RepositoryService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

// 动态构建BPMN
@SpringBootTest
@RunWith(SpringRunner.class)
public class MyTest02 {
    @Autowired
    RepositoryService repositoryService;

    @Test
    public void test01() {
        BpmnModel bpmnModel = new BpmnModel();

        Process process = new Process();
        process.setId("p_1");
        process.setName("p_1");

        StartEvent startEvent = new StartEvent();
        startEvent.setId("s_1");
        startEvent.setName("开始任务");

        process.addFlowElement(startEvent);

        UserTask userTask1 = new UserTask();
        userTask1.setId("u_1");
        userTask1.setName("请假申请");
        userTask1.setAssignee("小明");

        process.addFlowElement(userTask1);


        // 绘制连线
        SequenceFlow seq1 = new SequenceFlow();
        seq1.setSourceRef("s_1");
        seq1.setTargetRef("u_1");
        seq1.setId("seq1");
        process.addFlowElement(seq1);

        UserTask userTask2 = new UserTask();
        userTask2.setId("u_2");
        userTask2.setName("领导审批");
        userTask2.setAssignee("领导老王");

        process.addFlowElement(userTask2);

        // 绘制连线
        SequenceFlow seq2 = new SequenceFlow();
        seq2.setSourceRef("u_1");
        seq2.setTargetRef("u_2");
        seq2.setId("seq2");
        process.addFlowElement(seq2);

        EndEvent endEvent = new EndEvent();
        endEvent.setId("e_1");
        endEvent.setName("结束任务");
        process.addFlowElement(endEvent);
        // 绘制连线
        SequenceFlow seq3 = new SequenceFlow();
        seq3.setId("seq3");
        seq3.setSourceRef("u_2");
        seq3.setTargetRef("e_1");
        process.addFlowElement(seq3);

        bpmnModel.addProcess(process);
        // 查看执行后的xml格式
        BpmnXMLConverter converter = new BpmnXMLConverter();
        byte[] bytes = converter.convertToXML(bpmnModel);
        System.out.println(new String(bytes));

        repositoryService.createDeployment()
                .name("测试动态创建BPMNModel对象")
                .addBpmnModel("BPMNMODEL.bpmn", bpmnModel)
                .deploy();
    }
}
